package com.hzgj.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         //调用dopost方法:
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集编码
        req.setCharacterEncoding("utf-8");
        //获取请求中的数据:
        String user = req.getParameter("user");
        String pwd = req.getParameter("pwd");
        String jiZhu = req.getParameter("jiZhu");
        //判断登录是否成功: admin 123456
        if("admin".equals(user) && "123456".equals(pwd)){//登录成功
             //判断是否要记住密码
            if("1".equals(jiZhu)){//记住密码
             //把数据保存到cookie对象中
                Cookie uUser=new Cookie("user",user);
                Cookie uPwd=new Cookie("pwd",pwd);
                Cookie uJiZhu=new Cookie("jiZhu",jiZhu);
                //设置记住密码的时间
                uUser.setMaxAge(60);
                uPwd.setMaxAge(60);
                uJiZhu.setMaxAge(60);
                //把cookie添加到响应的客户端中
                resp.addCookie(uUser);
                resp.addCookie(uPwd);
                resp.addCookie(uJiZhu);
            }else{//忘记密码
                //把数据保存到cookie对象中
                Cookie uUser=new Cookie("user",user);
                Cookie uPwd=new Cookie("pwd",pwd);
                Cookie uJiZhu=new Cookie("jiZhu",jiZhu);
                //设置记住密码的时间
                uUser.setMaxAge(0);
                uPwd.setMaxAge(0);
                uJiZhu.setMaxAge(0);
                //把cookie添加到响应的客户端中
                resp.addCookie(uUser);
                resp.addCookie(uPwd);
            }
            //跳转到成功界面
            req.getRequestDispatcher("/success.jsp").forward(req,resp);
        }else{//登录失败
             resp.sendRedirect("/login.jsp");
        }
    }
}
